<template>
  <div class="login-container">
    <img src="../assets/img/background.jpg" alt="">
    <div class="right">
      <p class="right_title">艺术品交易网站</p>

      <!-- 登录页面 -->
      <div class="inputbox" v-if="showLogin">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="login"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="账户" prop="username">
            <el-input
              placeholder="Username"
              v-model="ruleForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              placeholder="Password"
              v-model="ruleForm.password"
              show-password
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="组别" prop="role">
            <el-select v-model="ruleForm.role" placeholder="role">
              <el-option label="艺术家" value="0"></el-option>
              <el-option label="普通用户" value="1"></el-option>
              <el-option label="管理员" value="2"></el-option>
            </el-select>
          </el-form-item> -->

          <div class="btn">
            <el-button type="primary" @click="handleLogin('login')"
              >立即登录</el-button
            >
            <el-button type="primary" @click.prevent="switchPage(1, 'login')"
              >前往注册</el-button
            >
          </div>
        </el-form>
      </div>

      <!-- 注册界面 -->
      <div class="inputbox" v-else>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="enroll"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="组别" prop="role">
            <el-select v-model="ruleForm.role" placeholder="role">
              <el-option label="艺术家" value="0"></el-option>
              <el-option label="普通用户" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="账户" prop="username">
            <el-input
              placeholder="Username"
              v-model="ruleForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              placeholder="Password"
              v-model="ruleForm.password"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              placeholder="phone"
              v-model="ruleForm.phone"
            ></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="real_name">
            <el-input
              placeholder="real_name"
              v-model="ruleForm.real_name"
            ></el-input>
          </el-form-item>

          <div class="btn">
            <el-button type="primary" @click.prevent="switchPage(0, 'enroll')">
              立即登录
            </el-button>
            <el-button type="primary" @click="handleRegister('enroll')"
              >确认注册</el-button
            >
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { Message } from "element-ui";
import { userLogin,userRegister } from "@/api/login.js";
import Cookies from "js-cookie";

export default {
  name: "LoginVue",
  data() {
    return {
      showLogin: true, // 登录注册切换变量
      validationMessage: "",
      validationMessageColor: "red",

      // 表单
      ruleForm: {
        username: "",
        password: "",
        real_name: "",
        phone: "",
        role: "",
      },
      test: false, //表单验证

      //登录组别

      // 验证规则
      rules: {
        username: [
          { required: true, message: "请输入您的用户名", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入您的密码", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入您的手机号", trigger: "blur" },
        ],
        real_name: [
          { required: true, message: "请输入您的真实姓名", trigger: "blur" },
        ],
        role: [
          { required: true, message: "请选择您的注册身份", trigger: "change" },
        ],
      },
    };
  },

  methods: {
    // 切换登录、注册
    switchPage(pageNum, ruleForm) {
      this.$refs[ruleForm].resetFields();
      this.showLogin = false;
      if (pageNum == 1) {
        this.showRegister = true;
      } else {
        this.showLogin = true;
      }
    },

    // 表单验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.test = true;
          return true;
        } else {
          this.test = false;
          return false;
        }
      });
    },

    // 登录
    async handleLogin(formName) {
      this.submitForm(formName);
      if (!this.test) return;
      try {
        let newdata = {
          username: this.ruleForm.username,
          password: this.ruleForm.password,
        };
        if (this.ruleForm.role === "0") {
          userLogin(newdata)
            .then(async (res) => {
              if (res.message ==  "登录成功") {
                Cookies.set("token", res.results.token);
                // 存储用户信息到vuex中
                this.$store.commit("setUser", res.results.user);
                Message({
                  message: "登录成功 正在为您跳转页面",
                  type: "success",
                });
                setTimeout(() => {
                  this.$router.push("/");
                }, 500);
              } else {
                Message({
                  message:
                    "请检查您的账号密码是否正确，并确定您选择了正确的组别",
                  type: "error",
                });
              }
            })
            .catch((err) => {
              Message({
                message: err,
                type: "error",
              });
            });
        } else if (this.ruleForm.role === "1") {
          userLogin(newdata)
            .then(async (res) => {
              if (res.message ==  "登录成功") {
                Cookies.set("token", res.results.token);
                // 存储用户信息到vuexl中
                this.$store.commit("setUser", res.results.user);
                Message({
                  message: "登录成功 正在为您跳转页面",
                  type: "success",
                });
                setTimeout(() => {
                  this.$router.push("/");
                }, 500);
              } else {
                console.log(res);
                Message({
                  message:
                    "请检查您的账号密码是否正确，并确定您选择了正确的组别",
                  type: "error",
                });
              }
            })
            .catch((err) => {
              Message({
                message: err,
                type: "error",
              });
            });
        } else {
          let newdata = {
            username: this.ruleForm.username,
            password: this.ruleForm.password,
          };
          userLogin(newdata)
            .then(async (res) => {
              if (res.message ==  "登录成功") {
                Cookies.set("token", res.results.token);
                // 存储用户信息到vuexl中
                this.$store.commit("setUser", res.results.user);
                Message({
                  message: "登录成功 正在为您跳转页面",
                  type: "success",
                });
                setTimeout(() => {
                  this.$router.push("/");
                }, 500);
              } else {
                Message({
                  message:
                    "请检查您的账号密码是否正确，并确定您选择了正确的组别",
                  type: "error",
                });
              }
            })
            .catch((err) => {
              Message({
                message: err,
                type: "error",
              });
            });
        }
      } catch (error) {
        Message({
          message: "网络出错啦",
          type: "error",
        });
      }
    },

    // 注册
    handleRegister(formName) {
      this.submitForm(formName);
      if (!this.test) return;

      if (this.ruleForm.role === "0") {
        let newdata = {
          username: this.ruleForm.username,
          password: this.ruleForm.password,
          real_name: this.ruleForm.real_name,
          phone: this.ruleForm.phone,
          role: this.ruleForm.role,
        };
        userRegister(newdata)
          .then((res) => {
            if (res.message == "注册成功") {
              Message({
                message: "注册成功，即将跳转登录页面",
                type: "success",
              });
              setTimeout(() => {
                this.showLogin = true;
              }, 500);
            } else {
              Message({
                message: res.message,
                type: "error",
              });
            }
          })
          .catch((err) => {
            Message({
              message: err,
              type: "error",
            });
          });
      } else if (this.ruleForm.role === "1") {
        let newdata = {
          username: this.ruleForm.username,
          password: this.ruleForm.password,
          real_name: this.ruleForm.real_name,
          phone: this.ruleForm.phone,
          role: this.ruleForm.role,
        };
        userRegister(newdata)
          .then((res) => {
            if (res.message == "注册成功") {
              Message({
                message: "注册成功，即将跳转登录页面",
                type: "success",
              });
              setTimeout(() => {
                this.showLogin = true;
              }, 500);
            } else {
              Message({
                message: res.message,
                type: "error",
              });
            }
          })
          .catch((err) => {
            Message({
              message: err,
              type: "error",
            });
          });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;

  // 输入框
  .right {
    position: absolute;
    right: 37%;
    top: 50%;
    transform: translateY(-50%);
    width: 25%;
    height: 480px;
    min-width: 400px;
    background: #fff;
    box-shadow: 0px 0px 10px #a4aab3;
    padding: 10px;

    .right_title {
      font-size: 30px;
      font-weight: bold;
      margin: 20px 0;
    }

    .inputbox {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      position: relative;
      height: 500px;
      padding-top: 5%;
      box-sizing: border-box;

      .input-box {
        width: 60%;
        height: 40px;
        margin: 25px auto 0;
        border: 1px solid #ccc;
        border-radius: 5px;
      }

      .input-box input[type="text"] {
        height: 100%;
        border: none;
        outline: none;
      }

      .btn {
        position: absolute;
        bottom: 120px;
        left: 50%;
        transform: translateX(-50%);

        .el-button {
          width: 45%;
        }
      }
    }
  }
}

.el-form.demo-ruleForm {
  padding-right: 5%;
}

.el-select {
  display: block;
}
</style>
